using Microsoft.EntityFrameworkCore;
using PandaWebAPI.Models.ef;

namespace PandaWebAPI.Services;

/// <summary>
/// 帖子标签服务实现
/// </summary>
public class PostTagService : IPostTagService
{
    private readonly PandaSystemContext _context;

    public PostTagService(PandaSystemContext context)
    {
        _context = context;
    }

    /// <inheritdoc />
    public async Task<IEnumerable<PostTag>> GetAllAsync()
    {
        return await _context.PostTags
            .Include(pt => pt.Post)
            .Include(pt => pt.Tag)
            .ToListAsync();
    }

    /// <inheritdoc />
    public async Task<PostTag?> GetByIdAsync(Guid id)
    {
        return await _context.PostTags
            .Include(pt => pt.Post)
            .Include(pt => pt.Tag)
            .FirstOrDefaultAsync(pt => pt.PostTagId == id);
    }

    /// <inheritdoc />
    public async Task<IEnumerable<PostTag>> GetByPostIdAsync(Guid postId)
    {
        return await _context.PostTags
            .Include(pt => pt.Post)
            .Include(pt => pt.Tag)
            .Where(pt => pt.PostId == postId)
            .ToListAsync();
    }

    /// <inheritdoc />
    public async Task<IEnumerable<PostTag>> GetByTagIdAsync(Guid tagId)
    {
        return await _context.PostTags
            .Include(pt => pt.Post)
            .Include(pt => pt.Tag)
            .Where(pt => pt.TagId == tagId)
            .ToListAsync();
    }

    /// <inheritdoc />
    public async Task<PostTag> CreateAsync(PostTag postTag)
    {
        postTag.PostTagId = Guid.NewGuid();
        _context.PostTags.Add(postTag);
        await _context.SaveChangesAsync();
        return postTag;
    }

    /// <inheritdoc />
    public async Task<PostTag> UpdateAsync(PostTag postTag)
    {
        _context.Entry(postTag).State = EntityState.Modified;
        await _context.SaveChangesAsync();
        return postTag;
    }

    /// <inheritdoc />
    public async Task DeleteAsync(Guid id)
    {
        var postTag = await _context.PostTags.FindAsync(id);
        if (postTag != null)
        {
            _context.PostTags.Remove(postTag);
            await _context.SaveChangesAsync();
        }
    }
} 